//
//  MYOauthViewController.swift
//  MYWeiBo
//
//  Created by apple on 16/5/13.
//  Copyright © 2016年 YanMo. All rights reserved.
//

import UIKit
import SVProgressHUD

class MYOauthViewController: UIViewController {
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action:"autoFill")
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.title = "登录"
        //使用webview来加载登录界面
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        //用进度条来显示进度
        SVProgressHUD.showInfoWithStatus("正在加载中")
        
    }
    //添加点击事件
    @objc private func autoFill(){
    
        //使用webview 来加载js代码
        let jsString = "document.getElementById('userId').value='13922070541';document.getElementById('passwd').value='happy13423589670';"
        //web来解析js
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
        
    }
    @objc private func close(){
        SVProgressHUD.dismiss()
        //把控制器关掉
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    //懒加载数据
    private lazy var webView : UIWebView = UIWebView()
  
}

//实现webview的代理方法
extension MYOauthViewController:UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //webview 每次调用的时候，都会回调的函数
    //返回true 可以加载，返回false 不可以加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //点击授权的时候会回调地址www.baidu.com
        // 点击授权: http://www.baidu.com/?code=46f61a46f57a8929fa4bb0c1a27a6e84
        // 点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        //取得url
        let url = request.URL!
        if !url.absoluteString.hasPrefix(redirect_uri){
            //不是回调地址，则是新浪的地址
            return true
        }else{
            //取得？后面的字符
            let query = url.query!
            let codeStrig = "code="
            if query.hasPrefix(codeStrig){
                //取得code的值.截取字符串
                let code = (query as NSString).substringFromIndex(codeStrig.characters.count)
                MYUserAccountModel.sharedInstance.loadAccountToken(code, errorCallBack: { (error) -> () in
                    if error != nil {
                        //授权出错了
                        SVProgressHUD.showErrorWithStatus("你的网络不给力...")
                        //延迟一秒
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    
                    }else{
                        //登录成功
                        //跳转到欢迎界面
                        // 调用AppDelegate的switchRootViewContriller
                        //取得appdelegate
                        MYPrint(items: "授权成功")
                        let appdelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
                        appdelegate.switchRootViewController(MYWelcomeViewController())
                        self.close()//关掉授权控制器
                    }

                })
                
            }else{
                //否则点击了取消按钮
                close()
            }
        }
        return false
    }
}
















